﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.Threading;
using System.ComponentModel;
using Microsoft.Win32.SafeHandles;
using System.Windows.Forms;
using System.Globalization;
using System.Diagnostics;

namespace PluginSurrogate
{
    public class SimulateModality
    {
        /// <summary>
        /// Windows won't let you be truly modal to a window in another
        /// thread/process. This method simulates modality by disabling
        /// the owner window until the action completes.
        /// </summary>
        /// <param name="owner">The window that "owns" the "modal" dialog.</param>
        /// <param name="action">An action that will be executed on a
        /// background thread while the foreground UI is disabled.</param>
        public static void ExecuteModally(IWin32Window owner, ThreadStart action)
        {
            EnableWindow(owner.Handle, false);
            try
            {
                using (EventWaitHandle waitHandle = new EventWaitHandle(false, EventResetMode.ManualReset))
                {
                    // Do the work on another thread, while we pump messages
                    // and wait for the event to be set.

                    ThreadStart ts = delegate
                    {
                        try
                        {
                            action();
                        }
                        catch (Exception e)
                        {
                            Trace.Fail(e.ToString());
                        }
                        finally
                        {
                            // Wake up the UI thread
                            waitHandle.Set();
                        }
                    };

                    new Thread(ts)
                    {
                        Name = "SimulatedModalityWorker",
                        IsBackground = false,
                        ApartmentState = ApartmentState.STA,
                        CurrentCulture = CultureInfo.CurrentCulture,
                        CurrentUICulture = CultureInfo.CurrentUICulture,
                        Priority = Thread.CurrentThread.Priority
                    }.Start();

                    // Pump messages and wait for waitHandle to be set
                    MsgLoopEventWait(waitHandle);
                }
            }
            finally
            {
                EnableWindow(owner.Handle, true);
            }
        }

        private static void MsgLoopEventWait(WaitHandle waitHandle)
        {
            using (SafeHandle hWait = waitHandle.SafeWaitHandle)
            {
                while (true)
                {
                    MSG msg;
                    while (PeekMessage(out msg, IntPtr.Zero, 0, 0, PM_REMOVE))
                    {
                        TranslateMessage(ref msg);
                        DispatchMessage(ref msg);
                    }

                    IntPtr hWaitNative = hWait.DangerousGetHandle();
                    int result = MsgWaitForMultipleObjects(1, ref hWaitNative, false, -1, QS_ALLINPUT);

                    if (result == WAIT_OBJECT_0 + 1)
                        continue;
                    else
                        break;
                }
            }
        }

        #region pinvoke declarations

        private const uint PM_REMOVE = 0x1;
        private const uint QS_ALLINPUT = 0x5FF;
        private const int WAIT_OBJECT_0 = 0x0;

        [DllImport("kernel32.dll", SetLastError = true)]
        static extern SafeHandleZeroOrMinusOneIsInvalid GetCurrentProcess();

        [DllImport("User32.dll")]
        static extern bool EnableWindow(IntPtr hcur, bool bEnable);

        [DllImport("user32.dll")]
        static extern bool PeekMessage(out MSG lpMsg, IntPtr hWnd, uint wMsgFilterMin, uint wMsgFilterMax, uint wRemoveMsg);

        [DllImport("user32.dll")]
        static extern bool TranslateMessage([In] ref MSG msg);

        [DllImport("user32.dll")]
        static extern IntPtr DispatchMessage([In] ref MSG msg);

        [DllImport("user32.dll")]
        static extern int MsgWaitForMultipleObjects(
            int nCount, // must be 1
            ref IntPtr pHandles,
            bool fWaitAll,
            int dwMilliseconds,
            uint dwWakeMask);

        struct MSG
        {
            IntPtr hwnd;
            uint message;
            uint wParam;
            uint lParam;
            uint time;
            POINT pt;
        }

        struct POINT
        {
            int x;
            int y;
        }

        #endregion
    }
}
